from selenium import webdriver
from time import sleep

'''
    *****爬取八维考试网站所有理论题目*****
    ***该源码仅提供单独使用，不参与服务器交互***
'''

#-----------参数设置-
time_wait = 0.1
course_name = '深度学习1'
# uname  = '18389100388'     # 输入的八维研修学院考试系统用户名
# upwd = '02020274'       # 输入的八维研修学院考试系统密码，默认密码为身份证后8位
uname  = '151601001249'     # 输入的八维研修学院考试系统用户名
upwd = '05011519'       # 输入的八维研修学院考试系统密码，默认密码为身份证后8位
savepath = 'all_lilun_html_titles/'     # 网页保存路径
#---------------

driver = webdriver.Chrome()
driver.get('http://172.16.10.111/exam/exam/studentScoreList1.do')

username = driver.find_element_by_xpath('//*[@id="username"]')
password = driver.find_element_by_xpath('//*[@id="password"]')

username.send_keys(uname)
password.send_keys(upwd)
sleep(7)

#最小化窗口
driver.minimize_window()
driver.set_window_size(1,1)

driver.switch_to.window(driver.window_handles[-1])
mygrade = driver.find_element_by_xpath('/html/body/div[1]/div/nav/ul/li[3]/a')
mygrade.click()

def Savehtml(name,content):
    print(name, content)
    with open(savepath + name+'.html','w',encoding='utf-8') as fw:
        fw.write(content)

query = driver.find_element_by_xpath('//*[@id="searchForm"]/table/tbody/tr[2]/td/input[1]')
query.click()
sleep(1)

pages = driver.find_elements_by_xpath('//*[@id="aazone.kslszone"]/div/ul/li/a')
pages = ['//*[@id="aazone.kslszone"]/div/ul/li['+str(i+1)+']/a' for i in range(len(pages))]
print('pages',pages)
for page in pages[2:-1]:
    print(page)
    page = driver.find_element_by_xpath(page)
    # print(page.text)
    page.click();
    sleep(time_wait)

    queryExams = driver.find_elements_by_xpath('//*[@id="aazone.kslszone"]/table/tbody/tr/td[11]/a')
    print(queryExams)
    for queryoneExam in queryExams:
        queryoneExam.click()
        sleep(time_wait)

        driver.switch_to.window(driver.window_handles[-1])
        name = driver.find_element_by_xpath('//*[@id="name"]').get_attribute('value')
        content = driver.page_source
        print(name)
        if name.find('理论') != -1 and name.find(course_name) != -1:
            Savehtml(name,content)
            # print(content)

        driver.close()
        driver.switch_to.window(driver.window_handles[-1])
    sleep(time_wait)

driver.close()



